package com.zhijiaoyun.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhijiaoyun.common.CommonUtils;
import com.zhijiaoyun.common.ResponseUtils;
import com.zhijiaoyun.common.ValidationUtils;
import com.zhijiaoyun.model.User;
import com.zhijiaoyun.oss.UserManager;
import com.zhijiaoyun.service.ILoginService;
import com.zhijiaoyun.service.IUserService;

/**
 * @author shisfish
 * @date 2017/12/15
 */
@Service(value = "loginService")
public class LoginServiceImpl implements ILoginService {

    @Autowired
    IUserService userService;

    @Override
    public Map<String, Object> userLogin(String email, String password, String device, HttpServletRequest request, HttpServletResponse response) {

        User user = userService.getUserByEmail(email);
        if (user == null) {
            return ResponseUtils.responseLoginError();
        }

        if (!user.getPassword().equals(CommonUtils.MD5(password))) {
            return ResponseUtils.responseLoginError();
        }

        Map<String, Object> map = new HashMap<>();
        String token = ValidationUtils.createJWT(user, ValidationUtils.DAY_MONTH);
        map.put("token", token);
        user.setPassword("");
        map.put("user", user);

        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(60 * 60 * 24 * 30);
        response.addCookie(cookie);

        UserManager.afterUserLogin(request, response, user, device);

        return ResponseUtils.responseSuccessMap(map);
    }
}
